import { Component, OnInit, ViewChild } from '@angular/core';
import { ModalDirective } from 'ngx-bootstrap/modal';
import { ConfigService } from '../../../core/common/config.service';
import { Http } from '@angular/http';
import { User } from '../../../core/auth/user.service';
import { Router } from '@angular/router';
import swal from 'sweetalert2';
import { TranslateService } from '@ngx-translate/core';

@Component({
    selector: 'app-paymoney',
    templateUrl: './paymoney.component.html',
    styleUrls: ['./paymoney.component.scss']
})
export class PayMoneyComponent implements OnInit {
    @ViewChild('chargeForm') public chargeForm;
    @ViewChild('payment') public payment: ModalDirective;
    // 保存页面所有表格相关数据
    public allDatas: any = {
        // 当前页面展示的渠道数据
        tableInfo: '',
        // 所有渠道费用明细表的数据
        tableDatas: '',
        // 条件筛选后的所有数据
        curTableDatas: '',
        // 缴费页面的数据
        payRecordsInfo: '',
        payRecordsDatas: '',
        curPayRecordsDatas: ''
    };
    // 渠道费用列表明细渠道名筛选参数
    public filtChnl = '';
    // 缴费相关的若干数据
    public chargeInfo = {
        chnl_id: '',
        chnl_name: '',
        type: '',
        value: '',
        errInfo: '',
        data: '0',
        able: true
    };
    // 渠道和渠道分类筛选的配置
    public chnlFilt: any = {
        name: '',
        cType: '2'
    };
    // 分页配置
    public config: any = {
        paging: true,
        itemsPerPage: 10,
        length: '',
        page: 1,
        maxSize: 5,
        firstText: '|<',
        previousText: '<<',
        nextText: '>>',
        lastText: '>|'
    };
    public configRe: any = {
        paging: true,
        itemsPerPage: 10,
        length: '',
        currentPage: 1,
        maxSize: 5
    };
    // 查询的起始日期
    public dateInfo: any = {
        begin: '',
        end: ''
    };
    // 日期插件的配置
    public datepickerOpts = {
        // minViewMode: 2,
        autoclose: true,
        required: true,
        todayBtn: false,
        todayHighlight: true,
        assumeNearbyYear: true,
        format: 'yyyy-mm-dd',
        startDate: '2017-04-01',
        endDate: new Date(),
        size: 'small',
        orientation: 'auto',
    };
    constructor(public user: User, private http: Http, private configService: ConfigService, private router: Router,
        private translate: TranslateService) {
        this.getNowFormatDate();
    }
    ngOnInit() {
        this.getChnlPayList();
    }
    // 默认的起始时间
    public getNowFormatDate() {
        const date = new Date();
        let month: any = date.getMonth() + 1;
        let strDate: any = date.getDate();
        if (month >= 1 && month <= 9) {
            month = '0' + month;
        }
        if (strDate >= 0 && strDate <= 9) { strDate = '0' + strDate; }
        this.dateInfo.end = date.getFullYear() + '-' + month + '-' + strDate;
        const cur_date = this.dateInfo.end.split('-');
        if (Number(cur_date[1]) < 2) {
            this.dateInfo.begin = (cur_date[0] - 1) + '-12-01';
        } else {
            let cur_month: any = cur_date[1] - 1;
            if (cur_month >= 1 && cur_month <= 9) { cur_month = '0' + cur_month; }
            this.dateInfo.begin = cur_date[0] + '-' + cur_month + '-01';
        }
    }
    // 缴费后表格和数据的初始化
    public chargeBtn() {
        this.chargeInfo.type = '1';
        this.chargeInfo.value = '';
        this.chargeInfo.data = '0';
        this.chargeInfo.errInfo = '';
        this.chargeInfo.able = true;
        this.chargeForm.reset();
        if (this.chargeInfo.chnl_id !== '') {
            this.payment.show();
        } else {
            this.translate.get('account.paymoney.chnlSelectWarning').subscribe((res: string) => {
                swal(res, '', 'error').catch(swal.noop);
            });
        }
    }
    // 获取渠道费用信息表
    public getChnlPayList() {
        const tabDatas_url = this.configService.get('url') + '?service=ChnlDepositService&method=getChnlDepositInfo';
        this.http.post(tabDatas_url, null).toPromise().then(data => {
            const infos = data.json();
            if (infos.code === '0000') {
                this.allDatas.tableDatas = infos.info;
                this.config.length = this.allDatas.tableDatas.length;
                this.allDatas.tableInfo = this.allDatas.tableDatas.slice(0, this.config.itemsPerPage);
            } else {
                console.log('chnlExpenses_require ERROR***  #code:' + infos.code + '  #info:' + infos.message);
            }
        });
    }
    // 提交缴费信息
    public chargeSubmit() {
        const payMoney: string = Number(this.chargeInfo.value).toFixed(2);
        this.translate.get('account.paymoney.promptInfo').subscribe((res: any) => {
            swal({
                title: res.areYouSure,
                text: res.curCharge + ' : ' + payMoney + ' ' + res.currencyUnit,
                type: 'warning',
                showCancelButton: true,
                cancelButtonText: res.cancel,
                confirmButtonColor: '#4C91EA',
                confirmButtonText: res.confirm
            }).then(() => {
                const chage_url = this.configService.get('url') + '?service=ChnlPayFeeService&method=chnlPayFee';
                this.http.post(chage_url, {
                    'chnl_id': this.chargeInfo.chnl_id, 'recv_fee': payMoney, 'remark': ''
                }).toPromise().then(data => {
                    if (data.json().code === '0000') {
                        const curPage = this.config.page;
                        swal({
                            title: res.chargeSuccess,
                            text: res.curCharge + ' : ' + payMoney + ' ' + res.currencyUnit,
                            type: 'success',
                            confirmButtonColor: '#3085d6',
                            confirmButtonText: res.confirm,
                            confirmButtonClass: 'btn btn-success',
                        }).then((e: any) => {
                            this.payment.hide();
                            this.getChnlPayList();
                        }, (dismiss: any) => {
                            this.payment.hide();
                            this.getChnlPayList();
                        }).then(
                            () => {
                                this.config.page = curPage;
                                this.chargeInfo.chnl_id = '';
                            }
                            );
                    } else {
                        this.chargeInfo.errInfo = res.error + ':' + data.json().message;
                    }
                });
            }).catch(swal.noop);
        });
    }
    // 获取历史缴费信息
    public searchPayRecords() {
        const beginDt: any = new Date(this.dateInfo.begin);
        const endDt: any = new Date(this.dateInfo.end);
        if (Date.parse(beginDt) > Date.parse(endDt)) { this.dateInfo.begin = this.dateInfo.end; }
        const records_url = this.configService.get('url') + '?service=ChnlPayLogService&method=getChnlPayLogInfo';
        this.http.post(records_url, {
            'start_date': this.dateInfo.begin, 'end_date': this.dateInfo.end,
            'pageNum': this.configRe.currentPage, 'pageSize': this.configRe.itemsPerPage
        }).toPromise().then(data => {
            const pInfos = data.json();
            if (pInfos.code === '0000') {
                this.allDatas.payRecordsInfo = pInfos.info.list;
                this.configRe.length = pInfos.info.total;
            } else {
                console.log('paymentHistory_require ERROR***  #code:' + pInfos.code + '  #info:' + pInfos.message);
            }
        });
    }
    // 渠道费用管理页面的数据筛选
    public filtChnlName(str: string): void {
        this.allDatas.curTableDatas = this.allDatas.tableDatas.filter((item: any) => {
            return item['chnl_name'].indexOf(str) >= 0;
        });
        this.allDatas.tableInfo = this.allDatas.curTableDatas.slice((this.config.page - 1) * this.config.itemsPerPage, this.config.page * this.config.itemsPerPage);
        this.config.length = this.allDatas.curTableDatas.length;
        const chnlIdArr = $(this.allDatas.tableInfo).map(function () {
            return this.chnl_id;
        }).get();
        if ($.inArray(this.chargeInfo.chnl_id, chnlIdArr) === -1) {
            this.chargeInfo.chnl_id = '';
        }
    }
    // 渠道费用管理页面的分页按钮功能
    public pageChanged(event: any): void {
        this.allDatas.tableInfo = this.allDatas.tableDatas.slice((event.page - 1) * this.config.itemsPerPage, event.page * this.config.itemsPerPage);
    };
    // 历史缴费信息页面的分页按钮功能
    public pageChangedRe(event: any): void {
        this.configRe.currentPage = event.page;
        this.searchPayRecords();
        // this.allDatas.payRecordsInfo = this.allDatas.curPayRecordsDatas.slice((event.page - 1) * this.configRe.itemsPerPage, event.page * this.configRe.itemsPerPage)
    };
    // 格式化货币
    public upDigit(n) {
        if (/^\d{1,8}(\.\d{0,2})?$/.exec(n) && (n > 0)) {
            this.chargeInfo.able = false;
            this.chargeInfo.data = n;
            this.chargeInfo.errInfo = '';
        } else {
            this.translate.get('account.paymoney.errInfo').subscribe((res: any) => {
                this.chargeInfo.errInfo = res;
            });
            this.chargeInfo.data = '0';
            this.chargeInfo.able = true;
        }
    }
    // 选择渠道缴费
    public checkChnl(event) {
        let elems: any;
        if ($(event).prop('tagName') === 'TD') {
            elems = $(event).parent();
        } else {
            elems = $(event).parent().parent();
        }
        elems.parent().find('.info').removeClass('info');
        elems.addClass('info').find(':radio').click();
    }
}
